package com.lfz.manage.controller;

import com.lfz.common.exception.MsgException;
import com.lfz.common.vo.SysResult;
import com.lfz.manage.pojo.Company;
import com.lfz.manage.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Daniel
 */
@RestController
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private CompanyService service;

    @GetMapping
    public SysResult listAll(){
        try {
            List<Company> list = service.listAll();
            return SysResult.oK(list);
        }catch (Exception e) {
            e.printStackTrace();
            return SysResult.OPERATE_FAILED;
        }
    }

    @GetMapping("/{compId}")
    public SysResult getCompanyById(@PathVariable String compId){
        try {
            Company company = service.getCompanyById(compId);
            return SysResult.oK(company);
        }catch (Exception e) {
            e.printStackTrace();
            return SysResult.OPERATE_FAILED;
        }
    }

    @PutMapping
    public SysResult addCompany(Company company){
        try {
            service.addCompany(company);
            return SysResult.oK();
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            SysResult result = SysResult.OPERATE_FAILED;
            result.setMsg("记录已经存在！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.OPERATE_FAILED;
        }
    }

    @PostMapping
    public SysResult updateCompany(Company company) {
        try {
            service.updateCompany(company);
            return SysResult.oK();
        } catch (MsgException e) {
            e.printStackTrace();
            SysResult result = SysResult.OPERATE_FAILED;
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.OPERATE_FAILED;
        }
    }

    @DeleteMapping("/{compId}")
    public SysResult deleteCompany(@PathVariable String compId){
        try {
            service.deleteCompany(compId);
            return SysResult.oK();
        } catch (MsgException e) {
            e.printStackTrace();
            SysResult result = SysResult.OPERATE_FAILED;
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.OPERATE_FAILED;
        }
    }



}
